<template>
    <div class="outbound-order-page">
      <!-- 数据筛选区域 -->
      <div class="filter-section">
        <el-row>
          <el-col :span="6">
            <el-form-item label="移库单号">
              <el-input v-model="page.TransferNum" placeholder="请输入/扫描单号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="单据类型" style="margin-left: 12px;">
              <el-select v-model="page.Transfer" placeholder="请选择">
                <el-option label="移库上架" :value="101"></el-option>
                        <el-option label="c" :value="102"></el-option>
                        <el-option label="报损移库" :value="103"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="移库单状态" style="margin-left: 12px;">
              <el-select v-model="page.TranAuditstatus" placeholder="请选择">
                <el-option label="待处理" :value="101"></el-option>
                <el-option label="处理中" :value="102"></el-option>
                <el-option label="已通过" :value="103"></el-option>
                <el-option label="已拒绝" :value="104"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="getoutprolist();" style="margin-left: 12px;">查询</el-button>
            <el-button @click="resetFilter">重置</el-button>
            <!-- <el-button type="text" class="advanced-search">高级搜索</el-button> -->
          </el-col>
        </el-row>
      </div>
  
      <!-- 数据列表区域 -->
      <div class="data-list-section">
        <el-row>
          <el-col :span="12">
            <el-button type="primary" @click="handleAdd">新增</el-button>
            <!-- <el-button @click="handleEdit">编辑</el-button> -->
            <el-button type="danger" @click="handleDeleteAll(selectedIds)">删除</el-button>
            <el-button type="success"  @click="handleRefresh">刷新</el-button>
            <!-- <el-button @click="handleExport">导出</el-button> -->
          </el-col>
        </el-row>
        <el-table :data="tableData" border style="width: auto" @selection-change="handleSelectionChange">
          <el-table-column type="selection"></el-table-column>
          <el-table-column prop="transferNum" label="订单号"></el-table-column>
          <el-table-column prop="productName" label="产品名称"  width="150px"></el-table-column>
          <el-table-column prop="productNum" label="产品编号"  width="150px"></el-table-column>
          <el-table-column prop="batch" label="批次"></el-table-column>
          <el-table-column prop="specifications" label="规格" width="150px"></el-table-column>
          <el-table-column prop="quantity" label="数量"></el-table-column>
          <el-table-column prop="originallocation" label="库位" width="150px">
            <template v-slot="scope">
              <p v-if="scope.row.originallocation==1">库位A</p>
              <p v-if="scope.row.originallocation==2">库位B</p>
              <p v-if="scope.row.originallocation==3">库位C</p>
            </template>
          </el-table-column>
          <el-table-column prop="transfer" label="出库类型 " width="150px">
            <template v-slot="scope">
              <p v-if="scope.row.transfer==101">移库上架</p>
              <p v-if="scope.row.transfer==102">仓库移库</p>
              <p v-if="scope.row.transfer==103">报损移库</p>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="customer" label="客户"></el-table-column> -->
          <el-table-column prop="tranCreator" label="制单人"></el-table-column>
          <el-table-column prop="tranAuditstatus" label="状态">
            <template v-slot="scope">
              <p v-if="scope.row.tranAuditstatus==101">待处理</p>
              <p v-if="scope.row.tranAuditstatus==102">处理中</p>
              <p v-if="scope.row.tranAuditstatus==103">已通过</p>
              <p v-if="scope.row.tranAuditstatus==104">已拒绝</p>
            </template>
          </el-table-column>
          <el-table-column prop="tranReviewer" label="审核人"></el-table-column>
          <el-table-column prop="tranAuditTime" label="审核时间"  width="150px"></el-table-column>
          <el-table-column label="操作" width="190px">
            <template #default="scope">
               <el-button link type="success" @click="handleView(scope.row)">查看</el-button>
             <el-button type="text" @click="handleEdit(scope.row.id)">编辑</el-button>
              <el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button>
              <!-- <el-button type="text" @click="handleAudit(scope.row)">审核</el-button>
              <el-button type="text" @click="handlePrint(scope.row)">打印</el-button> -->
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <div class="demo-pagination-block">
      <el-pagination
        v-model:current-page="page.pageindex"
        v-model:page-size="page.pageSize"
        :page-sizes="[15, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pages.totalcount"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        prev-text="上一页"
        next-text="下一页"
      />
    </div>
    </div>
  <!-- 出库详情 -->
  <el-dialog title="出库单详情" v-model="dialogFormVisible" width="60%">
       <!-- 上半部分信息 - 使用grid布局实现两列显示 -->
       <div class="detail-info-grid">
        <!-- 使用grid布局，每行两列 -->
        <div class="grid-row">
          <div class="grid-item">
            <span class="label">移库单号：</span>
            <span class="value">{{ form.transferNum }}</span>
          </div>
          <div class="grid-item">
            <span class="label">移库类型：</span>
            <span class="value">
              <template v-if="form.transfer==101">移库上架</template>
              <template v-if="form.transfer==102">移库上架</template>
              <template v-if="form.transfer==103">报损移库</template>
            </span>
          </div>
        </div>
        
        <div class="grid-row">
          <div class="grid-item">
            <span class="label">单据状态：</span>
            <span class="value">
              <template v-if="form.tranAuditstatus==101">待处理</template>
              <template v-if="form.tranAuditstatus==102">处理中</template>
              <template v-if="form.tranAuditstatus==103">已通过</template>
              <template v-if="form.tranAuditstatus==104">已拒绝</template>
            </span>
          </div>
          <div class="grid-item">
            <span class="label">关联单号</span>
            <span class="value">{{ form.associatedNum }}</span>
          </div>
        </div>
        
        <div class="grid-row">
          <div class="grid-item">
            <span class="label">制单人：</span>
            <span class="value">{{ form.tranCreator }}</span>
          </div>
        
   
          <div class="grid-item">
            <span class="label">制单日期：</span>
            <span class="value">{{ form.tranCreationTime.substring(0,10) }}</span>
          </div>
        </div>
        
        <div class="grid-row">
          <div class="grid-item">
            <span class="label">备注：</span>
            <span class="value">{{ form.rember }}</span>
          </div>
        </div>
        
        <!-- 审核原因单独一行 -->
        <div class="grid-row-full">
          <div class="grid-item">
            <span class="label">审核原因：</span>
            <span class="value">{{ form.shenRember || '同意' }}</span>
          </div>
        </div>
      </div>
  
      <!-- 下半部分表格 -->
      <el-table :data="tableDetails" style="margin-top: 20px;width:auto" border>
        <el-table-column prop="productNum" label="产品编码" />
        <el-table-column prop="productName" label="产品名称" />
        <el-table-column prop="specifications" label="规格" />
        <el-table-column prop="batch" label="批次" />
        <el-table-column prop="quantity" label="数量"  />
        <el-table-column prop="originallocation" label="当前库位" >
          <template v-slot="scope">
            <p v-if="scope.row.originallocation==1">仓库a;默认报损库位</p>
            <p v-if="scope.row.originallocation==2">仓库b;默认报损库位</p>
            <p v-if="scope.row.originallocation==3">仓库c;默认报损库位</p>
            <p v-if="scope.row.originallocation==4">仓库d;默认报损库位</p>
          </template>
        </el-table-column>
        <el-table-column prop="newlocation" label="移入库位" >
          <template v-slot="scope">
            <p v-if="scope.row.newlocation=='库位A'">仓库a;默认正式库位</p>
            <p v-if="scope.row.newlocation=='库位B'">仓库b;默认正式库位</p>
            <p v-if="scope.row.newlocation=='库位C'">仓库c;默认正式库位</p>
          </template>
        </el-table-column>
      </el-table>
  
      <div style="text-align: right; margin-top: 20px">
        <el-button @click="dialogFormVisible = false">关闭</el-button>
      </div>
  </el-dialog>
  </template>
  
  <script setup>
  import { ElRow, ElCol, ElFormItem, ElInput, ElSelect, ElOption, ElButton, ElTable, ElTableColumn } from 'element-plus';
  import axios from 'axios';
  import { ref, reactive, onMounted } from 'vue';
  import { saveAs } from 'file-saver';
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { useCounterStore } from "@/stores/counter";
  import {useRoute,useRouter} from 'vue-router'
  import { KongaUrl } from '@/axios/axiosHelp';
  
  // 模拟数据
  const mockData = ref([]);
  const page=reactive({
    TransferNum:'',
    Transfer:'',
    TranAuditstatus:'',
    pageindex:1,
    pageSize:15
  })
  const pages=reactive({
  totalpage:0,
  totalcount:0
  })
  onMounted(()=>{
    getoutprolist();
  })
  let router=useRouter();
  
  const getoutprolist=()=>{
  KongaUrl({
    url:'/activity/api/TranManagement/GetTranManagementQueryAll',
    method:'get',
    params:{
        TransferNum:page.TransferNum,
      Transfer:page.Transfer,
      TranAuditstatus:page.TranAuditstatus,
      pageindex:page.pageindex,
      pageSize:page.pageSize,
  
    }
  })
  .then(res=>{
   
      console.log(res)
      tableData.value=res.data.list;
      pages.totalcount=res.data.totalcount
      pages.totalpage=res.data.totalpage
      // 这里添加更新tableData
      // tableData.value = res.data;
  })
  }
  // 弹窗相关变量
  const dialogFormVisible  = ref(false);
  // 表格数据
  const tableData = ref(mockData.value);
  // 用于展示详情表格的数据，初始化为空数组
  const tableDetails = ref([]); 
  
  // 重置筛选条件方法
  const resetFilter = () => {
    page.outboundNumber = '';
    page.outbound = '';
    page.outAuditstatus = '';
    getoutprolist();
  };
  
  // 新增按钮点击方法
  const handleAdd = () => {
  router.push("/OutAddmanage")
    // 可在此添加打开新增表单等逻辑
  };
  
  // 编辑按钮点击方法
  const handleEdit = (id) => {
    console.log('传的数据',id)
    router.push({
      name:'UpdateTranManage',
      query:{
        id:id
      }
      
    })
    console.log('编辑操作', id);
    // 可在此添加打开编辑表单等逻辑
  };
  
  // 删除按钮点击方法
  const handleDelete = (row) => {
    ElMessageBox.confirm(
        '确定删除吗?',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
    .then(()=>{
      KongaUrl({
      url:'/activity/api/TranManagement/DeletTranmanage',
      method:'post',
      params:{
        id:row.id
      }
    })
    .then(res=>{
      if(res.status==200){
        ElMessage.success("删除成功")
        getoutprolist();
      }
    })
    })
    .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消',
            })
        })
  
    
    console.log('删除操作', row);
    // 可在此添加实际删除逻辑，如确认提示、后端请求等
  };
  
  const selectedIds = ref([])
  
  // 选择项变化
  const handleSelectionChange = (val) => {
    selectedIds.value = val.map(item => item.id)
    console.log('选中的数据', selectedIds.value)
  }
  
  // 批量删除操作
  const handleDeleteAll = (ids) => {
    console.log('选中批量的数据', ids.length)
    console.log('选中的数据', ids)
    
    if(ids.length === 0){
      ElMessage.error("请选择数据")
      return
    }
    
    ElMessageBox.confirm(
      `确定要删除选中的 ${ids.length} 条数据吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    .then(async () => {
      try {
        // 修正后的请求方式
        const response = await KongaUrl({
          url: '/activity/api/TranManagement/DeleteTranmanageALL',
          method: 'post',
          data:ids
        })
        
        if(response.status === 200) {
          ElMessage.success('删除成功')
          // 刷新数据
          getoutprolist();
        } 
      } catch (error) {
        ElMessage.error('删除失败: ' + error.message)
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
  }
  
  // 刷新按钮点击方法
  const handleRefresh = () => {
    getoutprolist();
  };
  
  // 导出按钮点击方法
  const handleExport = () => {
    console.log('导出操作');
    // 可在此添加实际导出逻辑，如调用后端接口生成文件等
  };
  
  
  const form = reactive({
  "pId": '',
  "transferNum": Math.floor(Math.random() * (999 - 100 + 1)) + 100,
  "associatedNum": "",
  "batch": "",
  "specifications": "",
  "quantity": 0,
  "totalprice": 0,
  "newlocation": "",
  "transfer": 0,
  "originallocation": "",
  "productName": "",
  "productNum": "",
  "tranAuditTime": "",
  "tranChangeTime": "",
  "tranAuditstatus":0,
  "tranCreator": "",
  "tranModifiedBy": '',
  "outAuditstatus": 0,
  "tranCreationTime": new Date().toISOString(),
  "rember": "",
  "shenRember": ""
  });
  
  
  // 添加解析花括号数据的方法
  const parseBracketData = (dataString) => {
    if (!dataString) return [];
    // 移除花括号并按逗号分隔
    return dataString.replace(/\{|\}/g, '').split(',').map(item => item.trim());
  };
  
  // 查看按钮点击方法
  const handleView = (row) => {
    console.log('查看行数据:', row);
    
    // 填充表单数据
    Object.assign(form, {
      pid: row.pId,
      transferNum: row.transferNum,
      associatedNum: row.associatedNum,
      batch: row.batch,
      specifications: row.specifications,
      quantity: row.quantity,
      totalprice: row.totalprice,
      newlocation: row.newlocation,
      outbound: row.outbound,
      tranAuditstatus: row.tranAuditstatus,
      productNum:row.productNum,
      productName:row.productName,
      tranCreator: row.tranCreator,
      reviewer: row.outReviewer,
      transfer:row.transfer,
      outAuditTime: row.outAuditTime,
      outAuditstatus: row.outAuditstatus,
      outCreationTime: row.outCreationTime,
      rember: row.rember,
      shenRember: row.shenRember,
      originallocation:row.originallocation
    });
  
    // 解析产品数据
    const productNums = parseBracketData(row.productNum);
    const productNames = parseBracketData(row.productName);
    const specificationes = parseBracketData(row.specifications);
    const batches = parseBracketData(row.batch);
    const prices = parseBracketData(row.price);
    const quantities = parseBracketData(row.quantity);
    const totalprices = parseBracketData(row.totalprice);
    const newlocations = parseBracketData(row.newlocation);
    const originallocations = parseBracketData(row.originallocation);
  
    // 构建详情表格数据
    tableDetails.value = productNums.map((productNum, index) => ({
      productNum: productNum,
      productName: productNames[index] || '',
      specifications: specificationes[index] || '',
      batch: batches[index] || '',
      price: parseFloat(prices[index]) || 0,
      quantity: parseFloat(quantities[index]) || 0,
      totalprice: parseFloat(totalprices[index]) || 0,
      newlocation: newlocations[index] || '',
      originallocation:originallocations[index]
    }));
  
    dialogFormVisible.value = true;
  };
  // 审核按钮点击方法
  const handleAudit = (row) => {
    console.log('审核操作', row);
    // 可在此添加实际审核逻辑，如调用后端接口等
  };
  
  // 打印按钮点击方法
  const handlePrint = (row) => {
    console.log('打印操作', row);
    // 可在此添加实际打印逻辑，如调用打印插件等
  };
  
  const handleSizeChange = (val) => {
    console.log(`${val} items per page`)
    page.pageSize=val;
    getoutprolist();
  
  }
  const handleCurrentChange = (val) => {
    console.log(`current page: ${val}`)
    page.pageindex=val;
    getoutprolist();
  }
  </script>
  
  <style scoped>
  /* 新增的grid布局样式 */
  .detail-info-grid {
    display: grid;
    grid-template-columns: 1fr;
    gap: 12px;
  }
  
  .grid-row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px;
  }
  
  .grid-row-full {
    grid-column: 1 / -1;
  }
  
  .grid-item {
    display: flex;
    min-width: 0;
  }
  
  .label {
    font-weight: bold;
    min-width: 80px;
    color: #606266;
  }
  
  .value {
    flex: 1;
    color: #303133;
    word-break: break-word;
  }
  .outbound-order-page {
    padding: 20px;
  }
  
  .filter-section {
    margin-bottom: 20px;
  }
  
  .data-list-section {
    border: 1px solid #e9e9e9;
    padding: 10px;
  }
  
  .advanced-search {
    margin-left: 10px;
    color: #409eff;
    text-decoration: underline;
  }
  </style>